using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Evolution.Engine.Managers;
using Evolution.GUI.Components;
using Microsoft.Xna.Framework.Input;

namespace Evolution.Engine.GUI
{
    public class EvolutionGuiSystem : Singleton<EvolutionGuiSystem>
    {
        public FormCollection Forms = new FormCollection();
        public Form this[string formName]
        {
            get
            {
                return Forms.FindByName(formName);
            }
        }

        public void AddForm(Form newForm)
        {
            Forms.Add(newForm);
        }

        public void Initialize()
        {
        }

        public void Update(GameTime gameTime)
        {
            MouseEventArgs mouseargs = new MouseEventArgs(
                InputManager.Instance.CurrentState,
                MouseButton.Left
            );

            KeyEventArgs keyargs = new KeyEventArgs(InputManager.Instance.Keys, InputManager.Instance.KeyboardState);

            foreach (Form form in Forms)
            {
                if (form.Visible)
                {
                    form.Update(gameTime);

                    if (InputManager.Instance.Dragging)
                    {
                        mouseargs.Button = InputManager.Instance.GetButtonPressed();
                        form.OnDragging(mouseargs);
                    }

                    if (InputManager.Instance.MouseDown() && !mouseargs.Handled)
                    {
                        mouseargs.Button = InputManager.Instance.GetButtonPressed();
                        form.OnMouseDown(mouseargs);
                    }

                    if (InputManager.Instance.MouseUp() && !mouseargs.Handled)
                    {
                        mouseargs.Button = InputManager.Instance.GetButtonReleased();
                        form.OnMouseUp(mouseargs);
                    }

                    if (InputManager.Instance.Keys.Count > 0)
                    {
                        form.OnKeyDown(keyargs);
                    }

                    InputManager.Instance.MouseHandled = mouseargs.Handled;
                }
            }
        }

        public void Draw(GameTime gameTime)
        {
            foreach (Form form in Forms)
                if (form.Visible)
                    form.Draw(gameTime);
        }

        public void LoadContent()
        {
            foreach (Form form in Forms)
                if (form.Visible)
                    form.LoadContent();
        }
    }
}
